package com.baorant.apigateway.filter;

import com.baorant.apigateway.Utis.IpUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class IPFilter extends ZuulFilter {
    private String[] whitelist;
    @Value("${filter.ip.whitelist}")
    private String strIPWhitelist;
    @Value("${filter.ip.whitelistenabled}")
    private String WhitelistEnabled;

        //	Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean shouldFilter() {
        if("true".equalsIgnoreCase(WhitelistEnabled))
        {
            System.out.println("IPFilter shouldFilter true");
            return true;
        } else {
            System.out.println("IPFilter shouldFilter false");
            return false;
        }
    }
	@Override
    public Object run() throws ZuulException {
        System.out.println("IPFilter");
        System.out.println(strIPWhitelist);
        whitelist = strIPWhitelist.split("\\,");

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req = ctx.getRequest();
        String ipAddr = IpUtil.getIpAddr(req);
        System.out.println("请求IP地址为：[" + ipAddr + "]");// 配置本地IP白名单，生产环境可放入数据库或者redis中
        List<String> ips = new ArrayList<String>();

        for (int i = 0; i < whitelist.length; ++i) {
            System.out.println(whitelist[i]);// 这里输出a b c
            ips.add(whitelist[i]);
        }

        System.out.println("whitelist：" + ips.toString());// 配置本地IP白名单，生产环境可放入数据库或者redis中
//        if (!ips.contains(ipAddr)) {
//            System.out.println("未通过IP地址校验.[" + ipAddr + "]");
//            ctx.setResponseStatusCode(401);
//            // 关键设置：停止Zuul转发
//            ctx.setSendZuulResponse(false);
//            ctx.getResponse().setContentType("application/json;charset=UTF-8");
//
//            ctx.setResponseBody("{\"errrocode\":\"00001\", \"errmsg\": \"IpAddr is forbidden![" + ipAddr + "]\"}");
//        }
        if (!ips.contains(ipAddr)) {
            System.out.println("未通过IP地址校验.[" + ipAddr + "]");
            // 设置响应状态码
            ctx.setResponseStatusCode(401);
            // 关键设置：停止Zuul转发
            ctx.setSendZuulResponse(false);
            // 获取HttpServletResponse
            HttpServletResponse response = ctx.getResponse();
            // 设置响应类型和字符编码
            response.setContentType("application/json;charset=UTF-8");
            // 设置响应体
            String responseBody = "{\"errorcode\":\"00001\", \"errmsg\": \"IpAddr is forbidden![" + ipAddr + "]\"}";
            try {
                // 确保响应被完整写入
                response.getWriter().write(responseBody);
                response.getWriter().flush();  // 刷新缓冲区
                response.getWriter().close();  // 关闭输出流
            } catch (IOException e) {
                System.err.println("写入响应失败: " + e.getMessage());
                // 即使写入失败，也要确保请求不被转发
                ctx.setSendZuulResponse(false);
            }

            // 额外设置，确保Zuul不会继续处理
            ctx.set("error.status_code", 401);
        }
        return null;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }
}
